//
//  NSString+SortNameUtils.m
//  beautyLamp
//
//  Created by Tam Kwok To Michael on 2017/8/19.
//  Copyright © 2017年 Tam Kwok To Michael. All rights reserved.
//

#import "NSString+SortNameUtils.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (SortNameUtils)

/**
 * 对数组按照首字母的拼音分组，并排序
 * @param lists 要分组的数组
 * @param objName 取数组中对象名称的函数
 * @param complement 分组完成后的回调函数
 */
+ (void) groupAndGetSectionTitles:(NSArray *)lists
                          objName:(NSString *(^)(id obj))objName
                       complement:(void (^)(NSArray<NSString *> *sectionTitles, NSArray<NSArray *> *groupLists))complement {
    
    if (!lists || !objName || !complement) return;
    
    NSMutableDictionary *groupDic = [NSMutableDictionary dictionary];
    //NSMutableArray *array = [NSMutableArray array];
    NSArray<NSString *> *sections = nil;
    NSMutableArray<NSArray *> *groups = [NSMutableArray array];
    
    // 按拼音首字母，对好友进行分组
    [lists enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        // 取对象名称
        NSString *name = objName(obj);
        // 取拼音首字母
        NSString *first = [name groupByFirstCharOfString];
        
        // 对对象进行分组
        NSMutableArray *array = [groupDic objectForKey:first];
        if (!array) {
            array = [NSMutableArray array];
            [groupDic setObject:array forKey:first];
        }
        [array addObject:obj];
    }];
    
    // 对分组进行排序
    if (groupDic.count) {
        NSArray *keys = groupDic.allKeys;
        NSArray *sortDesc = @[[[NSSortDescriptor alloc] initWithKey:nil ascending:YES]];
        sections = [keys sortedArrayUsingDescriptors:sortDesc];
    }
    
    // 将数据保存到分组
    [sections enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSArray *array = [groupDic objectForKey:obj];
        [groups addObject:array];
    }];
    
    // 回调数据
    complement(sections, groups);
}

+ (void) groupAndGetSectionTitles:(NSArray *)lists complement:(void (^)(NSArray<NSString *> *sectionTitles, NSArray<NSArray *> *groupLists))complement {
    
    if (!lists || !complement) return;
    
    NSMutableDictionary *groupDic = [NSMutableDictionary dictionary];
    //NSMutableArray *array = [NSMutableArray array];
    NSArray<NSString *> *sections = nil;
    NSMutableArray<NSArray *> *groups = [NSMutableArray array];
    
    // 按拼音首字母，对好友进行分组
    [lists enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        // 取对象名称
        NSString *name = obj;
        // 取拼音首字母
        NSString *first = [name groupByFirstCharOfString];
        
        // 对对象进行分组
        NSMutableArray *array = [groupDic objectForKey:first];
        if (!array) {
            array = [NSMutableArray array];
            [groupDic setObject:array forKey:first];
        }
        [array addObject:obj];
    }];
    
    // 对分组进行排序
    if (groupDic.count) {
        NSArray *keys = groupDic.allKeys;
        NSArray *sortDesc = @[[[NSSortDescriptor alloc] initWithKey:nil ascending:YES]];
        sections = [keys sortedArrayUsingDescriptors:sortDesc];
    }
    
    // 将数据保存到分组
    [sections enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSArray *array = [groupDic objectForKey:obj];
        [groups addObject:array];
    }];
    
    // 回调数据
    complement(sections, groups);
}



/**
 * string 取出首字声母
 */
- (NSString *)groupByFirstCharOfString {
    
    if (self == nil || [self length] == 0) return @"#";
    
    CFMutableStringRef str = CFStringCreateMutableCopy(NULL, 0, (CFStringRef)[self uppercaseString]);
    // 转成拼音
    CFStringTransform(str, NULL, kCFStringTransformToLatin, NO);
    // 去掉音标
    CFStringTransform(str, NULL, kCFStringTransformStripDiacritics, NO);
    CFStringRef cfstr = CFStringCreateCopy(NULL, str);
    NSString *py =  (__bridge_transfer NSString *)cfstr;
    unichar firstChar = [[py uppercaseString] characterAtIndex:0];
    if (!(firstChar >= 'A' && firstChar <= 'Z')) {
        firstChar = '#';
    }
    CFRelease(str);
    return [NSString stringWithFormat:@"%C", firstChar];
}


- (NSString *)md5String {
    const char *original_str = [self UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(original_str, (CC_LONG)self.length, result);
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]];
}

@end
